import { PostRiskEventService } from '../post-risk-event.service'
import { NzModalService } from 'ng-zorro-antd'
import { Component, OnInit, OnDestroy, ViewChild, TemplateRef } from '@angular/core'
import { DetailBaseClass } from '@shared/classes/DetailBaseClass'
import { STColumn } from '@delon/abc'
import { RuleTypeTextMap } from '@shared/interfaces/common'
import {
  PostRiskEventScheme,
  IPostRiskEventRuleTrade,
  PostRiskEventRule,
  IPostRiskEventRuleTradePagination,
  IPostRiskEventRuleTradeQueryParams,
} from '@shared/interfaces/postRisk-event'
import { ActivatedRoute, Router } from '@angular/router'
import { PageService } from '@shared/services/page.service'
import { NzMessageService } from 'ng-zorro-antd'
import { IDetailHeaderTab, StatusTextMap, Currency } from '@shared/interfaces/common'
import { DataService } from '@shared/services/data.service'
import { IBaseInfoColumn } from '@shared/interfaces/baseInfo'
import { ISearchOption } from '@shared/interfaces/search'
import { I18NService } from '@core'
import { StClass } from '@shared/classes/StClass'

@Component({
  selector: 'app-risk-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.less', '../../../shared/styles/table.less'],
})
export class PostRiskEventDeatilComponent extends DetailBaseClass<PostRiskEventScheme> implements OnInit, OnDestroy {
  RuleTypeTextMap = RuleTypeTextMap
  @ViewChild('tpCurrency') tpCurrency: TemplateRef<any>
  tabs: IDetailHeaderTab[] = [
    { text: this.trans('RISK_CTRL.RULES'), url: './rules' },
    { text: this.trans('GENERAL.INFO.BIZ_LEVEL'), url: './levels' },
  ]

  eventId: string
  intStoreCode: string
  riskCategoryOptions: ISearchOption[] = [
    { label: this.trans('RISK_CTRL_CATEGORY.NORMAL'), value: 'normal' },
    { label: this.trans('RISK_CTRL_CATEGORY.SPECIAL'), value: 'special' },
  ]

  thirdColumns: IBaseInfoColumn[] = []
  forthColumns: IBaseInfoColumn[] = []

  /* 风控规则列表 */
  ruleSt: StClass = new StClass({ page: 1, size: 1, count: 0, total: 0 })

  /* 交易列表 */
  tradeSt: StClass = new StClass({ page: 1, size: 5, count: 0, total: 0 })

  ruleTrades: IPostRiskEventRuleTrade[] = []

  ruleColumns: STColumn[] = [
    {
      type: 'link',
      title: '规则编号',
      i18n: 'RISK_CTRL.RULE.ID',
      index: 'ruleID',
      width: '150px',
      className: 'text-center',
      fixed: 'left',
      click: this.showRuleTrade.bind(this),
    },
    {
      title: '规则属性',
      i18n: 'GENERAL.INFO.RULE_TYPE',
      index: 'ruleType',
      width: '150px',
      className: 'text-center',
      fixed: 'left',
      render: 'ruleType',
    },
    {
      title: '规则描述',
      i18n: 'RISK_CTRL.RULE.DES',
      index: 'ruleName',
      width: '150px',
      className: 'text-center',
      fixed: 'left',
    },
    {
      title: '阈值描述',
      i18n: 'GENERAL.INFO.RULE_THRE_DESC',
      index: 'thresholdDesc',
      width: '150px',
      className: 'text-center',
      fixed: 'left',
    },
    {
      title: '阈值',
      i18n: 'GENERAL.INFO.RULE_THRE',
      index: 'threshold',
      width: '150px',
      className: 'text-center',
      fixed: 'left',
    },
    {
      title: '分值',
      i18n: 'GENERAL.INFO.SCORE',
      index: 'ruleScore',
      width: '150px',
      className: 'text-center',
      fixed: 'left',
    },
    {
      title: '更新时间',
      i18n: 'GENERAL.INFO.UPDATED_AT',
      index: 'updateTime',
      width: '150px',
      className: 'text-center',
      fixed: 'right',
    },
  ]

  tradeColumns = [
    {
      title: '订单号',
      i18n: 'TRADE.ORDER_NUM',
      index: 'orderNum',
      className: 'text-center',
      width: '150px',
      fixed: 'left',
    },
    {
      title: '交易时间',
      i18n: 'TRADE.TRANS_TIME',
      index: 'transDatetime',
      className: 'text-center',
      type: 'date',
      width: '150px',
      dateFormat: 'YYYY-MM-DD HH:mm',
    },
    {
      title: '交易场景',
      i18n: 'TRADE.TRANS_SCENE',
      className: 'text-center',
      width: '100px',
      index: 'transScene',
      render: 'transScene',
    },
    {
      title: '渠道',
      i18n: 'GENERAL.BIZ_LEVEL.CHANNEL',
      index: 'chanCode',
      className: 'text-center',
      width: '100px',
      render: 'transChannel',
    },
    {
      title: '交易金额',
      i18n: 'TRADE.TRANS_AMT',
      index: 'transAmt',
      className: 'text-center',
      width: '100px',
    },
    {
      title: '终端编号',
      i18n: 'GENERAL.TERMINAL.CODE',
      index: 'terminalID',
      className: 'text-center',
      width: '100px',
    },
    {
      title: '卡号',
      i18n: 'TRADE.CARD_NUMBER',
      index: 'acctNumSensitive',
      className: 'text-center',
      width: '100px',
      fixed: 'left',
    },
    {
      title: '授权码',
      i18n: 'POST.RISK.EVENT.AUTH_CODE',
      index: 'authCode',
      className: 'text-center',
      width: '100px',
      fixed: 'left',
    },
    {
      title: '检索参考号',
      i18n: 'OPERATION.TRADE.RETRIEVAL_REFNUM',
      index: 'retrivalRefNum',
      className: 'text-center',
      width: '100px',
      fixed: 'left',
    },
    {
      title: 'POS点输入方式码',
      i18n: 'POST.RISK.EVENT.SRYENTRY_MODE',
      index: 'srvEntryMode',
      className: 'text-center',
      width: '100px',
      fixed: 'left',
    },
    {
      title: '评论',
      i18n: 'GENERAL.INFO.COMMENT',
      index: 'remark',
      className: 'text-center',
      width: '100px',
      fixed: 'left',
    },
    {
      title: '操作',
      width: '100px',
      i18n: 'GENERAL.INFO.OPERATION',
      className: 'text-center p-xs',
      fixed: 'right',
      buttons: [
        {
          text: '',
          click: this.comment.bind(this),
          icon: {
            iconfont: 'icon-edit-twotone',
            type: 'iconfont',
          },
        },
      ],
    },
  ]
  storeScore: number
  handleStatus: string
  tradeQueryParams: IPostRiskEventRuleTradeQueryParams = {
    page: 1,
    size: 5,
  } as IPostRiskEventRuleTradeQueryParams
  /* modal */
  modal = {
    isCommentModalVisable: false,
    isModalLoading: false,
  }

  currentTrade: IPostRiskEventRuleTrade = {} as IPostRiskEventRuleTrade

  currentRule: PostRiskEventRule = {} as PostRiskEventRule

  constructor(
    public route: ActivatedRoute,
    public router: Router,
    public msg: NzMessageService,
    public pageService: PageService,
    private dataService: DataService,
    private i18n: I18NService,
    private postRiskEventService: PostRiskEventService,
    public modalService: NzModalService,
  ) {
    super(pageService)
  }

  ngOnInit() {
    this.loading = true
    this.eventId = this.route.snapshot.params['eventId']
    this.storeScore = this.route.snapshot.params['storeScore']
    this.intStoreCode = this.route.snapshot.params['intStoreCode']
    this.handleStatus = this.route.snapshot.params['handleStatus']
    this.initSt()
    this.initColumns()
    this.request()
  }

  ngOnDestroy() {
    this.pageService.triggerBaseEdit(false)
  }

  initSt() {
    this.tradeSt.stPage.front = false
  }

  initColumns() {
    this.initValue.call(this, this.firstColumns)
    this.initValue.call(this, this.secondColumns)
    this.initValue.call(this, this.thirdColumns)
    this.initValue.call(this, this.forthColumns)
  }

  request(): void {
    const queryParams = { eventID: this.eventId, intStoreCode: this.intStoreCode }
    this.postRiskEventService.getOne(queryParams).subscribe((postRiskEventScheme: PostRiskEventScheme) => {
      this.display(postRiskEventScheme)
      this.loading = false
    })
  }

  showRuleTrade(item: PostRiskEventRule, notFromRuleSt?: boolean) {
    if (this.currentRule && item.ruleId === this.currentRule.ruleId && !notFromRuleSt) return
    this.currentRule = item
    this.tradeSt.reset()
    const { eventRuleID } = item
    Object.assign(this.tradeQueryParams, { eventRuleID })
    this.getRuleTrades()
  }

  getRuleTrades() {
    this.postRiskEventService.getRuleTrades(this.tradeQueryParams).subscribe(res => {
      const { data, total } = res
      this.tradeSt.data = data
      this.tradeSt.total = total
    })
  }

  display(postRiskEventScheme: PostRiskEventScheme): void {
    console.log('postRiskEventScheme:', postRiskEventScheme)
    this.initRuleSt(postRiskEventScheme)
    this.renderRisk(postRiskEventScheme)
    this.initialColumns()
    this.initColumns()
  }

  initRuleSt(postRiskEventScheme: PostRiskEventScheme) {
    this.ruleSt.data = postRiskEventScheme.rules
    this.ruleSt.total = postRiskEventScheme.rules.length
  }

  initTradeSt(postRiskEventRuleTradePagination: IPostRiskEventRuleTradePagination) {
    const { data, total } = postRiskEventRuleTradePagination
    this.tradeSt.data = data
    this.tradeSt.total = total
  }

  renderRisk(postRiskEventScheme: any): void {
    this.detailData = postRiskEventScheme.storeInfo
    this.detailData.storeScore = this.storeScore
  }

  initialColumns(): void {
    this.firstColumns = [
      {
        span: 6,
        index: 'storeNum',
        label: 'GENERAL.STORE.NUM',
        labelI18n: 'GENERAL.STORE.NUM',
        disEditable: true,
      },
      {
        span: 6,
        index: 'storeName',
        label: 'GENERAL.STORE.NAME',
        labelI18n: 'GENERAL.STORE.NAME',
        disEditable: true,
      },
      {
        span: 6,
        index: 'storeNameEN',
        label: 'GENERAL.STORE.NAME_EN',
        labelI18n: 'GENERAL.STORE.NAME_EN',
        disEditable: true,
      },
      {
        span: 6,
        index: 'status',
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        displayValue: !this.detailData.status
          ? this.detailData.status
          : this.trans(StatusTextMap[this.detailData.status]),
        disEditable: true,
      },
    ]

    this.secondColumns = [
      {
        span: 12,
        index: 'contact.name',
        label: 'GENERAL.INFO.CONTACT_NAME',
        labelI18n: 'GENERAL.INFO.CONTACT_NAME',
        disEditable: true,
      },
      {
        span: 12,
        index: 'contact.email',
        label: 'GENERAL.INFO.CONTACT_MAIL',
        labelI18n: 'GENERAL.INFO.CONTACT_MAIL',
        disEditable: true,
      },
    ]
    this.thirdColumns = [
      {
        span: 6,
        index: 'address.nation',
        label: 'GENERAL.INFO.COUNTRY_REGION',
        labelI18n: 'GENERAL.INFO.COUNTRY_REGION',
        disEditable: true,
      },
      {
        span: 6,
        index: 'address.city',
        label: 'GENERAL.INFO.CITY',
        labelI18n: 'GENERAL.INFO.CITY',
        disEditable: true,
      },
      {
        span: 6,
        index: 'currencies',
        label: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        labelI18n: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        pipe: this.parseCurValue.bind(this),
        template: this.tpCurrency,
      },
      {
        span: 6,
        index: 'mcc',
        label: 'GENERAL.INFO.INDUSTRY_TYPE',
        labelI18n: 'GENERAL.INFO.INDUSTRY_TYPE',
        disEditable: true,
      },
    ]
    this.forthColumns = [
      {
        span: 12,
        index: 'address.address',
        label: 'GENERAL.INFO.ADDRESS',
        labelI18n: 'GENERAL.INFO.ADDRESS',
        disEditable: true,
      },
      {
        span: 12,
        index: 'storeScore',
        label: 'RISK_EVENT.SCORE',
        labelI18n: 'RISK_EVENT.SCORE',
        disEditable: true,
      },
    ]
  }

  // rule表换页
  onRuleChange($event) {}

  // trade表换页
  onTradeChange($event) {
    if ($event.type === 'pi') {
      const { pi: page, ps: size } = $event
      Object.assign(this.tradeQueryParams, { page, size })
      Object.assign(this.tradeSt, { pi: page, ps: size })
      this.getRuleTrades()
    }
  }

  parseCurValue(currencies: Array<Currency>): string {
    if (!currencies) return ''
    return currencies.map(c => c.code).join('、')
  }

  comment(item) {
    // if (item.status !== 'init') return
    this.currentTrade = item
    this.modal.isCommentModalVisable = true
  }

  handleModalCancel() {
    this.modal.isCommentModalVisable = false
    this.currentTrade.remark = ''
  }

  handleModalRemarkOk() {
    const { eventTransID, remark } = this.currentTrade
    this.postRiskEventService.updateRuleTrade({ eventTransID, remark }).subscribe(res => {
      this.showRuleTrade(this.currentRule, true)
      this.modal.isCommentModalVisable = false
    })
  }

  handleOperator(operator: string) {
    this.modalService.confirm({
      nzTitle: `make sure set the status: ${operator} ?`,
      nzOnOk: () => this.changeStatus(operator),
    })
  }

  changeStatus(operator: string) {
    const updateParams = { eventId: this.eventId, status: operator }
    this.postRiskEventService.updateStatus(updateParams).subscribe(res => {
      if (res) {
        this.msg.success(this.trans('TRADE_STATUS.RESOLVE'))
      } else {
        this.msg.error(this.trans('TRADE_STATUS.REJECT'))
      }
    })
  }

  trans(str: string, params?: Object): string {
    return this.i18n.fanyi(str, params)
  }
}
